// pages/component/tweet_list/tweet-list.js
import { 
  TWEET_LIST,
  TWEET_LIKE_REVERSE,
  TWEET_DELETE,
  TWEET_COMMENT,
 } from "../../request/api";
 import { 
   delHtmlTag
} from "../../utils/util";

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    listData:{
      type: Object,
      value: {
        type: 1,
        userId: '',
      },
      observer: function(newVal, oldVal){
        if(newVal.height){
          this.setData({
            listViewData: {
              height: newVal.height,
            }
          });
        }
        if(newVal.userId && newVal.type){
          this.setData({
            userId: newVal.userId,
            type: newVal.type,
          });
          this.loadMore();
        } else if(newVal.userId){
          this.setData({
            userId: newVal.userId,
          });
          if(this.data.dataList.length == 0){
            this.loadMore();
          }
        } else if(newVal.type){
          this.setData({
            type: newVal.type,
          });
        }

        if(newVal.enableComment){
          this.setData({
            enableComment: newVal.enableComment,
          })
        }
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    dataList:[],
    pageToken: '',
    userId: '',
    type: 1,
    enableComment: false,
    showCommentDialog: false,
    commentContent: '',
    selectId: 0,
    listViewData: {
      loadStatus: 2,
      height: 0,
    }
  },

  lifetimes: {
    attached: function () {
      // this.loadMore();
    },
    ready: function(){
      this.loadMore();
    },
    moved: function () {},
    detached: function () {},
  },


  // 组件所在页面的生命周期函数
  pageLifetimes: {
    show: function () {},
    hide: function () {},
    resize: function () {},
  },

  /**
   * 组件的方法列表
   */
  methods: {
    loadMore: function(){
      this._getTweets(this.data.userId, this.data.pageToken, this.data.type);
    },
    refresh: function(){
      this.data.pageToken = '';
      this.data.dataList = [];
      this.loadMore();
    },
    _getTweets: function(id, pageTokey, type){
      if(this.data.listViewData.loadStatus == 1){
        return;
      }
      this.data.listViewData.loadStatus = 1;
      var params;
      if(type == 3){
        if(!id){
          this.setLoadStatus(2);
          return;
        }
        params = {'authorId': id, 'pageToken': pageTokey};
      } else {
        params = {'pageToken': pageTokey, 'type': type};
      }
      
      TWEET_LIST(params).then(res => {
        if(res.data.code == 1){
          var result = res.data.result;
          var tempList = result.items;
          if(this.data.pageToken){
            tempList = this.data.dataList.concat(tempList);
          }
          this.setData({
            dataList: tempList,
            pageToken: result.nextPageToken,
            listViewData: {
              loadStatus: type == 2? 3 : result.totalResults <= tempList? 3 : 2,
            },
          })
        } else {
          this.setLoadStatus(2);
        }
      }).catch(res => {
        this.setLoadStatus(2);
      })
    },

    setLoadStatus: function(status){
      this.setData({
        listViewData: {
          loadStatus: status,
        },
      });
    },

    _reverseTweetLike: function(e){
      if (!this._checkLogin()) {
        return;
      }
      var sourceId = e.currentTarget.dataset.id;
      var index = e.currentTarget.dataset.index;
      TWEET_LIKE_REVERSE({'sourceId': sourceId}).then(res => {
        if(res.data.code == 1){
          var tempList = this.data.dataList;
          tempList[index].liked = res.data.result.liked;
          tempList[index].likeCount = res.data.result.likeCount;
          this.setData({
            dataList: tempList
          })
        }
      }).catch(err =>{})
    },
    _comment: function(e){
      if (!this._checkLogin()) {
        return;
      }
      if(!this.data.enableComment){
        return;
      }
      var sourceId = e.currentTarget.dataset.id;
      this.setData({
        showCommentDialog: true,
        selectId: sourceId,
      });
    },

    //取消按钮
    _cancelComment: function () {
      this.setData({
        showCommentDialog: false,
        selectId: 0,
      });
    },

    //确认
    _confirmComment: function (id, replyId, reAuthorId, type, commentContent) {
      if(this.data.commentContent.length == 0){
        this._showTips('请输入评论内容');
        return;
      }
      this.submitComment(this.data.selectId, 0, 0, 0, this.data.commentContent);
      this.setData({
        showCommentDialog: false,
        selectId: 0,
      });
    },

    _inputChange: function(e){
      this.data.commentContent = e.detail.value;
    },

    submitComment: function(id, replyId, reAuthorId, type, content){
      wx.showLoading({
        title: '正在提交...',
      });
      TWEET_COMMENT({
        'sourceId': id,
        // 'replyId': replyId,
        // 'reAuthorId': reAuthorId,
        // 'type': type,
        'content': content,
      }).then(res => {
        wx.hideLoading({
          success: (res) => {},
        });
        this._showTips(res.data.message);
        this.data.commentContent = '';
      }).catch(err => {
        wx.hideLoading({
          success: (res) => {},
        });
        this._showTips("评论失败");
      });
    },

    deleteTweet: function(id, index){
      TWEET_DELETE({'sourceId': id}).then(res => {
        if(res.data.code == 1){
          this.data.dataList.splice(index, 1);
          this.setData({
            dataList: this.data.dataList,
          });
        } else {
          this._showTips(res.data.message);
        }
      }).catch(err => {

      });
    },

    _checkLogin: function () {
      var app = getApp();
      if (!app.globalData.isLogin) {
        wx.showModal({
          content: '您还没有登录，请登录',
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/account/login/login',
              });
            } else if (res.cancel) {
  
            }
          }
        });
        return false;
      } else {
        return true;
      }
    },

    _toDetail: function (e) {
      // var data = e.currentTarget.dataset;
      var index = e.currentTarget.dataset.index;
      var data = this.data.dataList[index];
        var dataStr = JSON.stringify(data);
        wx.navigateTo({
          url: '/pages/tweet/detail/detail?tweet=' + encodeURIComponent(dataStr),
        });
    },
    _toUserProfile: function(e){
      var id = e.currentTarget.dataset.id;
      if(id){
        wx.navigateTo({
          url: '/pages/user/user?userId='+id,
        });
      }
    },
    _doNothing: function(e){},
    _showTips: function(msg){
      wx.showToast({
        title: msg,
        icon: 'none'
      })
    },
    _showActionSheet: function(e){
      var that = this;
      var dataset = e.currentTarget.dataset;
      var authorId = dataset.authorid+'';
      var deletable = authorId == this.data.userId;
      wx.showActionSheet({
        itemList: deletable? ['复制','删除'] : ['复制'],
        success (res) {
          console.log(res.tapIndex)
          if(res.tapIndex == 0){
            var content = dataset.content;
            wx.setClipboardData({
              data: delHtmlTag(content),
            });
          } else if(res.tapIndex == 1){
            var id = dataset.id;
            var index = dataset.index;
            that.showDeleteConfirmDialog(id, index);
          }
        },
      })
    },
    
    showDeleteConfirmDialog: function(id, index){
      var that = this;
      wx.showModal({
        content: '您确定要删除吗？',
        success (res){
          if (res.confirm) {
            that.deleteTweet(id, index);
          }
        }
      })
    },
  }
})
